import Taro from "@tarojs/taro";
import { MINX_URL } from "./config";

export default ({ url = "", method = "GET", data = {}, header = {} } = {}) => {
  return new Promise((resolve, reject) => {
    Taro.request({
      url: MINX_URL(url),
      data: data,
      header: Object.assign(
        {
          "Content-Type": "application/json",
        },
        header
      ),
      method: method.toUpperCase(),
    }).then((res) => {
      const { statusCode, data } = res;
      if (/\/contract\/captcha64/.test(url)) {
        let cookie = res.header.Cookie || res.header.cookie;
        console.log(cookie);
        Taro.setStorageSync("cookie", cookie);
      }
      if (statusCode >= 200 && statusCode < 300) {
        try {
          if (data.hasOwnProperty("error_code")) {
            let code = data.error_code;
            switch (code) {
              case 0:
                resolve(data);
                break;
              default:
                /**
                 * -1: token error; 1: token is null
                 */
                reject(new Error(data.message));
            }
          } else if (data.hasOwnProperty("code")) {
            let code = data.code;
            switch (code) {
              case 0:
                resolve(data);
                break;
              case 1:
                if (/\/appletSigning2\/whetherSignedSuccess/.test(url)) {
                  resolve(data);
                } else {
                  reject(new Error(data.msg));
                }
                break;
              case 4:
                if (
                  /\/appletSigning2\/verifySms/.test(url) &&
                  data.msg === "此手机号码已注册"
                ) {
                  resolve(data);
                } else {
                  reject(new Error(data.msg));
                }
                break;
              case 2020:
                if (/\/appletSigning2\/findPersonal/.test(url)) {
                  resolve(data);
                } else {
                  reject(new Error(data.msg));
                }
              default:
                /**
                 * 1 获取失败
                 */
                reject(new Error(data.msg));
            }
          } else {
            resolve(data);
          }
        } catch (e) {
          Taro.showToast({
            title: `${e}`,
            icon: "none",
            mask: true,
          });
        }
      } else {
        reject(new Error(`网络请求错误，状态码${statusCode}`));
        throw new Error(`网络请求错误，状态码${statusCode}`);
      }
    });
  });
};
